package com.budwk.app.sqfwV2.component.centuryCity;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.Asserts;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplateExcelCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwV2.constants.CenturyCitySecurityConstant;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckGasDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.enums.*;
import com.budwk.app.sqfwV2.enums.jinYang.JinYangExcelEnum;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
@IocBean
public class CenturyCitySecurityExcelService extends SqfwTemplateExcelCommonService {

    private final Map<String, String> mapFileIndex = new ConcurrentHashMap<>();

    @Inject
    private SysDictService dictService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SysUserService userService;

    @Override
    public List<GenerateExcelUrlVO> generateExcel(List<ExcelCreateConfig> excelConfigList, String userId, List<String> sqfwIdList) {
        mapFileIndex.put(SecurityUtil.getUserId(), excelConfigList.get(0).getFileIdentity());
        return super.generateExcel(excelConfigList, userId, sqfwIdList);
    }


    /**
     * 允许自定义生成excel的原材料，
     *
     * @param baseExcelParam 生成excel提供的原材料
     * @param userId         用户id
     * @param sqfwIdList     社区服务id列表
     */
    @Override
    protected void customerPopularBaseExcelParam(BaseExcelParamDTO baseExcelParam, String userId, List<String> sqfwIdList) {

    }

    @Override
    protected void customerPopularBaseExcelParamForAdmin(BaseExcelParamDTO baseExcelParam, String userId, List<String> formSummaryNewIdList) {

    }

    /**
     * 组装需要下载的excel 生成类
     *
     * @param excelConfigList
     * @param baseExcelParam
     * @return
     */
    @Override
    protected List<ExcelGeneratorConfig> getExcelCodeGeneratorConfig(List<ExcelCreateConfig> excelConfigList, BaseExcelParamDTO baseExcelParam) {
        log.info("dayinglu excel getExcelCodeGeneratorConfig: {}", JSONObject.toJSONString(excelConfigList));
        if (excelConfigList.size() == 0) {
            return Collections.emptyList();
        }
        Map<String, Object> param = excelConfigList.get(0).getParam();
        Object source = null;
        if (ObjectUtils.isNotEmpty(param)) {
            source = param.get("source");
        }
        List<ExcelGeneratorConfig> list = new ArrayList<>();
        for (ExcelCreateConfig config : excelConfigList) {
            ExcelGeneratorConfig generatorConfig = new ExcelGeneratorConfig();
            generatorConfig.setExcelCreateConfig(config);
            BaseTemplateExcelGenerator service = CenturyCitySafeServiceEnum.getService(config.getFileIdentity());
            //2.0版本兼容
            if ("V2".equals(source)) {
                service = CenturyCitySafeV2ServiceEnum.getService(config.getFileIdentity());
            }
            if (service != null) {
                generatorConfig.setGenerator(service);
                list.add(generatorConfig);
            }

            // 宇虹
            if (service == null) {
                service = YuHongEnum.getService(config.getFileIdentity());
                if (service != null) {
                    generatorConfig.setGenerator(service);
                    list.add(generatorConfig);
                }
            }
            // 宾阳街道
            BaseTemplateExcelGenerator baseTemplateExcelGenerator = BinYangFileServiceEnum.getService(config.getFileIdentity());
            if (baseTemplateExcelGenerator != null) {
                generatorConfig.setGenerator(baseTemplateExcelGenerator);
                list.add(generatorConfig);
            }
            // 金阳 新增燃气使用统计表
            BaseTemplateExcelGenerator jinYangService = JinYangExcelEnum.getService(config.getFileIdentity());
            if (jinYangService != null) {
                generatorConfig.setGenerator(jinYangService);
                list.add(generatorConfig);
            }

        }

        return list;
    }

    @Override
    protected AbstractCustomerPdfCreateField parseParamData(String paramDataStr) {
        return JSONObject.parseObject(paramDataStr, SafeCheckTaskPdfDTO.class);
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    protected String getSqfwFormSummaryType() {
        return SupportBusinessTypeEnum.SAFE_CHECK.getName();
    }

    /**
     * 这个方法用户可以自定义重写，在这个方法中可以根据sqfwId进行查询
     *
     * @param sqfwIdList 社区服务id list
     * @return 结果
     */
    protected List<Sqfw_formSummary_new> queryForSummaryData(List<String> sqfwIdList, Map<String, Object> param) {
        String fileIndex = mapFileIndex.get(SecurityUtil.getUserId());
        String type = CenturyCitySafeServiceEnum.getType(fileIndex);
        //金阳 新增excel
        JinYangExcelEnum jinYangEnum = JinYangExcelEnum.getJinYangEnum(fileIndex);
        if (ObjectUtils.isNotEmpty(jinYangEnum)) {
            //是否走原来基础类的处理方式
            if (!jinYangEnum.isUseOriginalMethod()) {
                //新增的excel数据查询方式不一样
                return sqfwFormsummaryNewService.queryJinYangGasUse(param, SupportBusinessTypeEnum.SAFE_CHECK.getName());
            } else {
                type = jinYangEnum.getType();
            }
        }
        if (StringUtils.isEmpty(type)) {
            // 去宾阳街道获取
            BinYangFileServiceEnum serviceEnum = BinYangFileServiceEnum.getByCode(fileIndex);
            if (serviceEnum != null) {
                //新版观山湖app 2.0走这个条件
                if (param.containsKey("fillStartDate")) {
                    //观山湖2.0版本 根据条件查询数据
                    return sqfwFormsummaryNewService.queryByCondition(param, SupportBusinessTypeEnum.SAFE_CHECK.getName());
                } else {
                    return sqfwFormsummaryNewService.queryBySqfwIdsAndType(sqfwIdList, SupportBusinessTypeEnum.SAFE_CHECK.getName());
                }
            }
            // 宇虹
            type = YuHongEnum.getType(fileIndex);
        }
        if (sqfwIdList.size() == 0) return Collections.emptyList();
        String sqfwFormSummaryType = getSqfwFormSummaryType();
        if (StringUtils.isBlank(sqfwFormSummaryType)) Asserts.fail("forSummary类型不能为空");
        Cnd cnd = Cnd.NEW();
        //新版观山湖app 2.0走这个条件
        if (param.containsKey("fillStartDate")) {
            if (ObjectUtils.isNotEmpty(param.get("fillStartDate"))) {
                cnd.and(Sqfw_formSummary_new::getFillDate, ">", String.format("%s 00:00:00", param.get("fillStartDate")));
            }
            if (ObjectUtils.isNotEmpty(param.get("fillEndDate"))) {
                cnd.and(Sqfw_formSummary_new::getFillDate, "<", String.format("%s 23:59:59", param.get("fillEndDate")));
            }
            if (ObjectUtils.isNotEmpty(param.get("shopInfoId"))) {
                cnd.and(Sqfw_formSummary_new::getShopsBaseInfoId, "=", param.get("shopInfoId"));
            }

            Sys_user user = userService.getUserById(SecurityUtil.getUserId());
            //拼接五级 省
            cnd.and(Sqfw_formSummary_new::getProvince, "=", user.getProvince());
            //拼接五级 市
            cnd.and(Sqfw_formSummary_new::getCity, "=", user.getCity());
            //拼接五级 区
            cnd.and(Sqfw_formSummary_new::getDistrict, "=", user.getDistrict());
            //拼接五级 街道
            cnd.and(Sqfw_formSummary_new::getCounty, "=", user.getCounty());
            //拼接五级 社区
            cnd.and(Sqfw_formSummary_new::getCommunity, "=", user.getCommunity());
        } else {
            cnd.and("sqfw_id", "in", sqfwIdList);
        }
        cnd.and("type", "=", sqfwFormSummaryType);
        cnd.and("param_data ->> 'type'", "in", "'" + type + "'");
        if (CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode().equals(fileIndex)) {
           /* List<String> typeList= new ArrayList<>();
            typeList.add(CenturyCitySafePlaceTypeEnum.RESTAURANT.getName());
            typeList.add(CenturyCitySafePlaceTypeEnum.SHOP.getName());
            cnd.and("param_data ->> 'placeType'", "in", typeList)*/
            cnd.and("param_data->>'fileOutputType'", "<>", "[\"-1\"]");
        }
        cnd.orderBy("fill_date", "asc");
        List<Sqfw_formSummary_new> sqfwFormSummaryNewS = sqfwFormsummaryNewService.query(cnd);
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList;

        // 宇虹
        if (YuHongEnum.BACK_PAY.getCode().equals(fileIndex)) {
            sqfwFormSummaryNewList = sqfwFormSummaryNewS;
        } else {
            //燃气不需要在这里构建参数
            if (!CenturyCitySafeServiceEnum.CENTER_CITY_GAS_SAFE.getCode().equals(fileIndex)) {
                sqfwFormSummaryNewList = buildFormSummaryParam(sqfwFormSummaryNewS, type, fileIndex, "APP");
            } else {
                //燃气
                sqfwFormSummaryNewList = buildGasFormSummaryParam(sqfwFormSummaryNewS);
            }
        }
        mapFileIndex.remove(SecurityUtil.getUserId());
        return sqfwFormSummaryNewList;
    }

    public List<Sqfw_formSummary_new> buildGasFormSummaryParam(List<Sqfw_formSummary_new> sqfwFormSummaryNewS) {
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = new ArrayList<>();
        for (Sqfw_formSummary_new sqfwItem : sqfwFormSummaryNewS) {
            SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sqfwItem.getParamData(), SafeCheckTaskPdfDTO.class);
            SafeCheckGasDTO safeCheckGasDTO = safeCheckTaskPdfDTO.getSafeCheckGasDTO();
            if (ObjectUtils.isEmpty(safeCheckGasDTO)) continue;
            CenturyCitySafeCheckGasUseEnum centuryCitySafeCheckGasUseEnum = CenturyCitySafeCheckGasUseEnum.getEnum(safeCheckGasDTO.getFireAndElectricityUsage());
            if (ObjectUtils.isNotEmpty(centuryCitySafeCheckGasUseEnum)) {
                sqfwFormSummaryNewList.add(sqfwItem);
            }
        }
        return sqfwFormSummaryNewList;
    }

    public List<Sqfw_formSummary_new> buildFormSummaryParam(List<Sqfw_formSummary_new> sqfwFormSummaryNewS, String type, String fileIndex, String sourceType) {

        Sys_user user = userService.getUserById(SecurityUtil.getUserId());

        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = new ArrayList<>();
        //由异常改为全部正常后不计入文件
        Set<String> idSet = new HashSet<>();
        //先分组 这里分组获取只争对改版后的数据，条件是shopsBaseInfoId跟WorkOrderId 是同一个值直接按店铺分组
        Map<String, List<Sqfw_formSummary_new>> mapFormSummary = sqfwFormSummaryNewS.stream().filter(s -> StringUtils.isNotBlank(s.getShopsBaseInfoId()) && s.getShopsBaseInfoId().equals(s.getWorkOrderId())).collect(Collectors.groupingBy(Sqfw_formSummary_new::getShopsBaseInfoId));
        //先分组 这里分组获取只争对老版的数据，条件是shopsBaseInfoId跟WorkOrderId 不是同一个值，先按任务分组再按店铺分组
        Map<String, Map<String, List<Sqfw_formSummary_new>>> mapFormSummaryOld = sqfwFormSummaryNewS.stream().filter(s -> StringUtils.isNotBlank(s.getShopsBaseInfoId()) && !s.getShopsBaseInfoId().equals(s.getWorkOrderId())).collect(Collectors.groupingBy(Sqfw_formSummary_new::getSqfwId, Collectors.groupingBy(Sqfw_formSummary_new::getShopsBaseInfoId)));

        //再排序
       /* for (Map.Entry<String, List<Sqfw_formSummary_new>> nmap : mapFormSummary.entrySet()) {
            nmap.getValue().sort(Comparator.comparing(Sqfw_formSummary_new::getCreateDate));
        }*/
        Map<String, List<Sqfw_formSummary_new>> map = sqfwFormSummaryNewS.stream().collect(Collectors.groupingBy(s -> JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getPlaceName()));


        for (Sqfw_formSummary_new sqfwItem : sqfwFormSummaryNewS) {

            boolean flagHiddenDangers = true;
            SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sqfwItem.getParamData(), SafeCheckTaskPdfDTO.class);
            String address = safeCheckTaskPdfDTO.getAddress();
            if (StringUtils.isNotBlank(safeCheckTaskPdfDTO.getPlot())) {
                if (StringUtils.isNotBlank(safeCheckTaskPdfDTO.getAddress())) {
                    address = String.format("%s(%s)", safeCheckTaskPdfDTO.getPlot(), safeCheckTaskPdfDTO.getAddress());
                } else {
                    address = safeCheckTaskPdfDTO.getPlot();
                }
            }
            safeCheckTaskPdfDTO.setAddress(address);
            List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOList = safeCheckTaskPdfDTO.getHiddenDanger();
            List<SafeCheckTaskParamDataDTO> otherHiddenDangers = safeCheckTaskPdfDTO.getOtherHiddenDangers();
            if (CollectionUtil.isNotEmpty(otherHiddenDangers) && !CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode().equals(fileIndex)) {
                for (SafeCheckTaskParamDataDTO otherHiddenDanger : otherHiddenDangers) {
                    if ("已整改".equals(otherHiddenDanger.getKey()) && !"1".equals(otherHiddenDanger.getRectificationType())) {
                        continue;
                    }
                    flagHiddenDangers = false;
                    Sqfw_formSummary_new item = new Sqfw_formSummary_new();
                    BeanUtil.copyProperties(sqfwItem, item);
                    SafeCheckTaskPdfDTO pdfDTO = new SafeCheckTaskPdfDTO();
                    BeanUtil.copyProperties(safeCheckTaskPdfDTO, pdfDTO);
                    if ("5".equals(otherHiddenDanger.getRectificationType())) {
                        Sqfw_formSummary_new sqfwFormSummaryNew = map.get(safeCheckTaskPdfDTO.getPlaceName()).stream().sorted(Comparator.comparing(Sqfw_formSummary_new::getCreateDate))
                                .collect(Collectors.toList()).stream().filter(s -> s.getCreateDate().after(sqfwItem.getCreateDate())).findFirst().orElse(null);
                        if (ObjectUtil.isNotEmpty(sqfwFormSummaryNew)) {
                            SafeCheckTaskPdfDTO checkTaskPdfDTO = JSONObject.parseObject(sqfwFormSummaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
                            if (CollectionUtil.isNotEmpty(checkTaskPdfDTO.getOtherHiddenDangers())) {
                                Map<String, List<SafeCheckTaskParamDataDTO>> stringListMap = checkTaskPdfDTO.getOtherHiddenDangers().stream().collect(Collectors.groupingBy(s -> s.getRiskCode()));
                                otherHiddenDanger.setDispositionNineSmallPlaces(stringListMap.get(otherHiddenDanger.getRiskCode()).get(0).getKey().equals("已整改") ? "已整改" : "整改中");
                                otherHiddenDanger.setRectificationBackPhoto(stringListMap.get(otherHiddenDanger.getRiskCode()).get(0).getRectificationBackPhoto());
                                idSet.add(sqfwFormSummaryNew.getId());
                            }
                        } else {
                            otherHiddenDanger.setDispositionNineSmallPlaces(otherHiddenDanger.getKey().equals("已整改") ? "已整改" : "整改中");
                        }
                    } else {
                        otherHiddenDanger.setDispositionNineSmallPlaces(otherHiddenDanger.getKey().equals("已整改") ? "已整改" : "整改中");
                    }

                    otherHiddenDanger.setNineSmallPlacesIssuesAndRisks(otherHiddenDanger.getRiskDesc());


                    otherHiddenDanger.setReportNineSmallPlaces("已告知");
                    List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOS = new ArrayList<SafeCheckTaskParamDataDTO>() {
                        {
                            add(otherHiddenDanger);
                        }
                    };
                    pdfDTO.setHiddenDanger(safeCheckTaskParamDataDTOS);
                    item.setParamData(JSONUtil.toJsonStr(pdfDTO));
                    sqfwFormSummaryNewList.add(item);
                }


            }


            for (SafeCheckTaskParamDataDTO dto : safeCheckTaskParamDataDTOList) {
                HiddenDangerEnum hiddenDangerEnum = HiddenDangerEnum.getHiddenDangerEnum(dto.getRiskCode(), fileIndex);

                if (ObjectUtils.isEmpty(hiddenDangerEnum)) continue;
                //if (CenturyCitySafeServiceEnum.CENTER_CITY_NINE_SMALL_PLACE.getCode().equals(fileIndex)) {
                if (fileIndex.contains(CenturyCitySafeServiceEnum.CENTER_CITY_NINE_SMALL_PLACE.getCode())) {
                    if (CenturyCitySafePlaceTypeEnum.RESTAURANT.getCode().equals(hiddenDangerEnum.getType())) {
                        continue;
                    }
                    //九小场所-消防栓是否配备水枪，水带 只做记录不计入问题
                    if (HiddenDangerEnum.isHydrantOperational.getCode().equals(dto.getRiskCode())) {
                        continue;
                    }

                }
                //人员密集下-食堂问题不进入人员密集excel
                if (CenturyCitySafeServiceEnum.CENTER_CITY_PERSONNEL_DENSITY.getCode().equals(fileIndex)) {
                    if (hiddenDangerEnum.getType().contains(CenturyCitySafePlaceTypeEnum.canteen.getCode())) {
                        continue;
                    }
                }
                Sqfw_formSummary_new item = new Sqfw_formSummary_new();
                BeanUtil.copyProperties(sqfwItem, item);
                SafeCheckTaskParamDataDTO sctp = new SafeCheckTaskParamDataDTO();
                BeanUtil.copyProperties(dto, sctp);

                if (hiddenDangerEnum.getFlag().equals(sctp.getKey())) {
                    //特殊处理 是否使用新型燃料(如:醇基)
                    if (HiddenDangerEnum.isNewFuelUsed.getCode().equals(sctp.getRiskCode())) {
                        sctp.setNineSmallPlacesIssuesAndRisks(hiddenDangerEnum.getResult());
                        flagHiddenDangers = false;
                        sctp.setRiskLevel(CenturyCitySecurityConstant.WU);
                        sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.WU);
                        sctp.setReportNineSmallPlaces(CenturyCitySecurityConstant.YGZ);
                        List<SafeCheckTaskParamDataDTO> safeCheckTaskPdfDTOS3 = new ArrayList<>();
                        safeCheckTaskPdfDTOS3.add(sctp);
                        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO3 = new SafeCheckTaskPdfDTO();
                        BeanUtil.copyProperties(safeCheckTaskPdfDTO, safeCheckTaskPdfDTO3);
                        safeCheckTaskPdfDTO3.setHiddenDanger(safeCheckTaskPdfDTOS3);
                        item.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO3));
                        sqfwFormSummaryNewList.add(item);
                    } else {
                        //九小场所食品其他情况由客户自动填写
                        if (HiddenDangerEnum.foodOtherInformation.getCode().equals(sctp.getRiskCode())) {
                            sctp.setNineSmallPlacesIssuesAndRisks(sctp.getFoodOtherInformation());
                        } else {
                            sctp.setNineSmallPlacesIssuesAndRisks(hiddenDangerEnum.getResult());
                        }
                        flagHiddenDangers = false;
                        boolean flag = StringUtils.isNotBlank(sctp.getRectificationTypeCode()) ? RectificateTimeEnum.IMMEDIATE_RECTIFICAIOTN.getCode().equals(sctp.getRectificationTypeCode()) : RectificateTimeEnum.IMMEDIATE_RECTIFICAIOTN.getName().equals(sctp.getRectificationType());
                        if (flag) {
                            sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.YZG);
                        } else {
                            sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.ZGZ);
                            //当是限期整改时需找到指向下一条的记录看状态是否已整改
                            Sqfw_formSummary_new lastFormSummary = null;
                            //app 2.0的新版数据走这个,其他走下面的数据
                            // if ("APP".equals(sourceType) && StringUtils.isNotBlank(sqfwItem.getWorkOrderId()) && sqfwItem.getWorkOrderId().equals(sqfwItem.getShopsBaseInfoId())) {
                            if ("APP".equals(sourceType)) {
                                //app 下载是根据整个任务时间下载，是连续的因此可以用上面的缓存变更记录状态
                                if (StringUtils.isNotBlank(sqfwItem.getWorkOrderId()) && sqfwItem.getWorkOrderId().equals(sqfwItem.getShopsBaseInfoId())) {
                                    //新版2.0走这大个，新版只有任务分组
                                    lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode(), user, mapFormSummary);
                                } else {
                                    //老板数据兼容走这个，原因是老版数据有任务概念，所以上面先根据任务分组再根据场所分组
                                    //从上面分组的mapFormSummaryOld中取对应任务的值
                                    Map<String, List<Sqfw_formSummary_new>> mapOld = mapFormSummaryOld.get(sqfwItem.getSqfwId());
                                    lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode(), user, mapOld);
                                }
                            } else {
                                //web 走这个，当是勾选数据下载时可能会跳开因此需要查库变更状态
                                lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode());
                            }

                            if (null != lastFormSummary) {
                                SafeCheckTaskPdfDTO safeCPD = JSONObject.parseObject(lastFormSummary.getParamData(), SafeCheckTaskPdfDTO.class);
                                List<SafeCheckTaskParamDataDTO> safeCTPDataDTOList = safeCPD.getHiddenDanger();
                                for (SafeCheckTaskParamDataDTO sctpd : safeCTPDataDTOList) {
                                    if (sctp.getRiskCode().equals(sctpd.getRiskCode()) && !hiddenDangerEnum.getFlag().equals(sctpd.getKey())) {
                                        //item.setFillDate(lastFormSummary.getFillDate());
                                        sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.YZG);
                                        sctp.setRectificationBackPhoto(sctpd.getRectificationBackPhoto());
                                        idSet.add(lastFormSummary.getId());
                                        break;
                                    }
                                }
                            }
                        }
                        sctp.setReportNineSmallPlaces(CenturyCitySecurityConstant.YGZ);
                        sctp.setRiskLevel(StringUtils.isNotBlank(sctp.getRiskLevel()) ? sctp.getRiskLevel() : CenturyCitySecurityConstant.YBYH);
                        List<SafeCheckTaskParamDataDTO> safeCheckTaskPdfDTOS3 = new ArrayList<>();
                        safeCheckTaskPdfDTOS3.add(sctp);
                        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO3 = new SafeCheckTaskPdfDTO();
                        BeanUtil.copyProperties(safeCheckTaskPdfDTO, safeCheckTaskPdfDTO3);
                        safeCheckTaskPdfDTO3.setHiddenDanger(safeCheckTaskPdfDTOS3);
                        item.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO3));
                        sqfwFormSummaryNewList.add(item);
                    }
                }
            }

            //重点场所||楼宇处理（针对灭火器）
            if (CenturyCitySafeServiceEnum.CENTER_CITY_KEY_LOCATION.getCode().equals(fileIndex) || CenturyCitySafeServiceEnum.CENTER_CITY_BUILDING_HAZARDS.getCode().equals(fileIndex)) {
                if (HiddenDangerEnum.fireNum.getFlag().equals(safeCheckTaskPdfDTO.getPlaceFireExtinguishersNumber())) {
                    flagHiddenDangers = false;
                    SafeCheckTaskParamDataDTO sctp = new SafeCheckTaskParamDataDTO();
                    sctp.setRiskLevel(CenturyCitySecurityConstant.YBYH);
                    //sctp.setRiskImages(CenturyCitySecurityConstant.WU);
                    sctp.setNineSmallPlacesIssuesAndRisks(HiddenDangerEnum.fireNum.getResult());
                    sctp.setReportNineSmallPlaces(CenturyCitySecurityConstant.YGZ);
                    sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.ZGZ);
                    //当是限期整改时需找到最新记录看状态是否已整改
                    //Sqfw_formSummary_new lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode());
                    //当是限期整改时需找到指向下一条的记录看状态是否已整改
                    Sqfw_formSummary_new lastFormSummary = null;
                    //app 2.0的新版数据走这个,其他走下面的数据
                    if ("APP".equals(sourceType)) {
                        //app 下载是根据整个任务时间下载，是连续的因此可以用上面的缓存变更记录状态
                        if (StringUtils.isNotBlank(sqfwItem.getWorkOrderId()) && sqfwItem.getWorkOrderId().equals(sqfwItem.getShopsBaseInfoId())) {
                            //新版2.0走这大个，新版只有任务分组
                            lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode(), user, mapFormSummary);
                        } else {
                            //老板数据兼容走这个，原因是老版数据有任务概念，所以上面先根据任务分组再根据场所分组
                            //从上面分组的mapFormSummaryOld中取对应任务的值
                            Map<String, List<Sqfw_formSummary_new>> mapOld = mapFormSummaryOld.get(sqfwItem.getShopsBaseInfoId());
                            lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode(), user, mapOld);
                        }
                    } else {
                        //web 走这个，当是勾选数据下载时可能会跳开因此需要查库变更状态
                        lastFormSummary = selectLastFormSummary(sqfwItem, safeCheckTaskPdfDTO, type, fileIndex, sctp.getRiskCode());
                    }

                    if (null != lastFormSummary) {
                        SafeCheckTaskPdfDTO safeCPD = JSONObject.parseObject(lastFormSummary.getParamData(), SafeCheckTaskPdfDTO.class);
                        if (!HiddenDangerEnum.fireNum.getFlag().equals(safeCPD.getPlaceFireExtinguishersNumber())) {
                            sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.YZG);
                            idSet.add(lastFormSummary.getId());
                        }
                    }
                    List<SafeCheckTaskParamDataDTO> safeCheckTaskPdfDTOS = new ArrayList<>();
                    safeCheckTaskPdfDTOS.add(sctp);
                    SafeCheckTaskPdfDTO safeCheckTaskPdfDTO2 = new SafeCheckTaskPdfDTO();
                    BeanUtil.copyProperties(safeCheckTaskPdfDTO, safeCheckTaskPdfDTO2);
                    safeCheckTaskPdfDTO2.setHiddenDanger(safeCheckTaskPdfDTOS);
                    sqfwItem.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO2));
                    sqfwFormSummaryNewList.add(sqfwItem);
                }
            }
            if (flagHiddenDangers) {
                if (!idSet.isEmpty() && idSet.contains(sqfwItem.getId())) continue;
                SafeCheckTaskParamDataDTO sctp = new SafeCheckTaskParamDataDTO();
                sctp.setRiskLevel(CenturyCitySecurityConstant.WU);
                //sctp.setRiskImages(CenturyCitySecurityConstant.WU);
                sctp.setRectificationMeasure(CenturyCitySecurityConstant.WU);
                sctp.setNineSmallPlacesIssuesAndRisks(CenturyCitySecurityConstant.WU);
                sctp.setReportNineSmallPlaces(CenturyCitySecurityConstant.WU);
                sctp.setDispositionNineSmallPlaces(CenturyCitySecurityConstant.WU);
                List<SafeCheckTaskParamDataDTO> safeCheckTaskPdfDTOS = new ArrayList<>();
                safeCheckTaskPdfDTOS.add(sctp);
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO2 = new SafeCheckTaskPdfDTO();
                BeanUtil.copyProperties(safeCheckTaskPdfDTO, safeCheckTaskPdfDTO2);
                safeCheckTaskPdfDTO2.setHiddenDanger(safeCheckTaskPdfDTOS);
                sqfwItem.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO2));
                sqfwFormSummaryNewList.add(sqfwItem);
            }
        }
        return sqfwFormSummaryNewList;
    }

    private Sqfw_formSummary_new selectLastFormSummary(Sqfw_formSummary_new sqfwItem, SafeCheckTaskPdfDTO safeCheckTaskPdfDTO, String type, String fileIndex, String code) {
        Cnd cnd = Cnd.NEW();
        //勾选的数据是新版的时候需要根据场所去查询，当是老数据时需要根据任务去查询
       /* if (StringUtils.isNotBlank(sqfwItem.getWorkOrderId()) && sqfwItem.getWorkOrderId().equals(sqfwItem.getShopsBaseInfoId())) {
            cnd.and("shops_base_info_id", "=", sqfwItem.getShopsBaseInfoId());
        } else {
            cnd.and("sqfw_id", "=", sqfwItem.getSqfwId());
        }*/
        cnd.and("shops_base_info_id", "=", sqfwItem.getShopsBaseInfoId());
        cnd.and("type", "=", sqfwItem.getType());
        cnd.and("param_data ->> 'type'", "in", "'" + type + "'");
        //zhangp  九小场所-餐饮-健康证特殊处理
        if (CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode().equals(fileIndex)) {
            cnd.and("param_data->>'fileOutputType'", "<>", "[\"-1\"]");
        }
        //新版本根据店铺ID查就行，兼容老版本数据
        if (!sqfwItem.getShopsBaseInfoId().equals(sqfwItem.getWorkOrderId())) {
            cnd.and("param_data ->> 'placeName'", "=", safeCheckTaskPdfDTO.getPlaceName());
        }

        cnd.and("create_date ", ">", sqfwItem.getCreateDate());
        cnd.orderBy(" create_date", "asc");
        return sqfwFormsummaryNewService.fetch(cnd);
    }

    private Sqfw_formSummary_new selectLastFormSummary(Sqfw_formSummary_new sqfwItem, SafeCheckTaskPdfDTO safeCheckTaskPdfDTO, String type, String fileIndex, String code, Sys_user user, Map<String, List<Sqfw_formSummary_new>> map) {
        //从上面分组的map中取对应场所的值
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = map.get(sqfwItem.getShopsBaseInfoId());
        //排序
        sqfwFormSummaryNews.sort(Comparator.comparing(Sqfw_formSummary_new::getCreateDate));
        Sqfw_formSummary_new sqfwFormSummaryNew = null;
        //循环找到当前指向的下一条
        for (Sqfw_formSummary_new item : sqfwFormSummaryNews) {

            //九小场所-餐饮-健康证特殊处理
            if (CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode().equals(fileIndex)) {
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO1 = JSONObject.parseObject(item.getParamData(), SafeCheckTaskPdfDTO.class);
                if (!safeCheckTaskPdfDTO1.getFileOutputType().contains("-1")) {
                    if (sqfwItem.getCreateDate().before(item.getCreateDate())) {
                        sqfwFormSummaryNew = item;
                        break;
                    }
                }
            } else {
                if (sqfwItem.getCreateDate().before(item.getCreateDate())) {
                    sqfwFormSummaryNew = item;
                    break;
                }
            }
        }
        return sqfwFormSummaryNew;
    }
}



